<?php

namespace App\Http\Controllers\V1\Auth;

use App\Models\V1\AdminUser;
use Jenssegers\Agent\Agent;
use Illuminate\Http\Request;
use App\Events\V1\AdminLoginEvent;
use App\Http\Controllers\Controller;
use App\Http\Requests\V1\AdminLoginRequest;
use Illuminate\Foundation\Auth\AuthenticatesUsers;
use Log;

class AuthController extends Controller
{
    use AuthenticatesUsers;

    // 用户登录成功跳转路由
    protected $redirectTo = 'admin/index';
    // 用户登出成功跳转路由
    protected $redirectAfterLogout = 'show.login';

    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    /**
     * 重写AuthenticatesUsers中的username()
     * 设置登录验证用户名
     *
     * @return string
     */
    public function username()
    {
        return 'code';
    }

    /**
     * 重写AuthenticatesUsers中的showLoginForm()
     * 显示登录页面
     *
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showLoginForm()
    {
        return view('v1.login');
    }

    /**
     * 重写AuthenticatesUsers中的login()
     * 处理登录请求
     *
     * @param AdminLoginRequest $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Http\Response
     */
    public function login(AdminLoginRequest $request)
    {
        $code = $request->get('code');
        $user = AdminUser::where('code',$code)->first();
        $is_staff = false;
        if (!empty($user) || isset($user)) {
            $is_staff = $user->is_staff;
        }
        $request['is_staff'] = $is_staff;
        $this->validateLogin($request);

        if ($this->hasTooManyLoginAttempts($request)) {
            $this->fireLockoutEvent($request);
            return $this->sendLockoutResponse($request);
        }

        if ($this->attemptLogin($request)) {
            return $this->sendLoginResponse($request);
        }

        $this->incrementLoginAttempts($request);

        return $this->sendFailedLoginResponse($request);
    }

    /**
     * 重写AuthenticatesUsers中的validateLogin()
     * 验证用户登录请求
     *
     * @param AdminLoginRequest $request
     */
    protected function validateLogin(AdminLoginRequest $request)
    {
        if ($request->method() === 'POST') {
            $rules = $request->rules();
            $rules['captcha'] = 'bail|required|captcha';
            $rules['is_staff'] = 'accepted';
            $messages = $request->messages();
            $messages['is_staff.accepted'] = '登录账号不存在';
            // 执行表单数据验证
            $this->validate($request, $rules, $messages);
        }
    }

    /**
     * 重写AuthenticatesUsers中的sendLoginResponse()
     * 发送登录成功响应
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse
     */
    protected function sendLoginResponse(Request $request)
    {
        $request->session()->regenerate();

        $this->clearLoginAttempts($request);

        return $this->authenticated($request, $this->guard()->user())
            ?: redirect()->intended($this->redirectPath());
    }

    /**
     * 重写AuthenticatesUsers中的sendLoginResponse()
     * 发送登录失败响应
     *
     * @param Request $request
     * @return $this|\Illuminate\Http\JsonResponse
     */
    protected function sendFailedLoginResponse(Request $request)
    {
        $errors = [$this->username() => '登录失败，鉴权信息不匹配'];

        if ($request->expectsJson()) {
            return response()->json($errors, 422);
        }

        return redirect()->back()
            ->withInput($request->only($this->username(), 'remember'))
            ->withErrors($errors);
    }

    /**
     * 重写AuthenticatesUsers中的authenticated()
     * 处理用户认证通过后，执行相关后续业务逻辑
     *
     * @param Request $request
     * @param $user
     */
    protected function authenticated(Request $request, $user)
    {
        // 登录成功，触发事件
        $req['reqIp'] = $request->getClientIp();

        $rsp['rspStatus'] = true;
        $rsp['rspMsg'] = '【' . $user["code"] . '】登录成功！';

        event(new AdminLoginEvent(new Agent(), $req, $rsp));
    }

    /**
     * 重写AuthenticatesUsers中的logout()
     * 处理登出请求
     *
     * @param Request $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->invalidate();

        return redirect()->route($this->redirectAfterLogout);
    }
}
